﻿namespace JobButenko.Controllers
{
    using System.Web.Mvc;
    using System.Web.Routing;

    using JobButenko.Models;
    using JobButenko.Models.BusinessLogicLayer;

    public class AccountController : Controller
    {
        // GET: /Account/
        private readonly DataManager dataManager;

        public AccountController(DataManager dataManager)
        {
            this.dataManager = dataManager;
        }

        private IFormsAuthenticationService FormsService { get; set; }

        private IRoleService RoleService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (this.FormsService == null)
            {
                this.FormsService = new FormsAuthenticationService();
            }

            if (this.RoleService == null)
            {
                this.RoleService = new AccountRoleService();
            }

            base.Initialize(requestContext);
        }

        public ActionResult Register()
        {
            this.ViewData["Roles"] = new SelectList(this.dataManager.Role.GetRoles(), "RoleId", "RoleName");
            return View();
        }

        [HttpPost]
        public ActionResult Register(UserModel model, int roleId)
        {
            this.ViewData["Roles"] = new SelectList(this.dataManager.Role.GetRoles(), "RoleId", "RoleName");
            if (ModelState.IsValid)
            {
                if (model != null)
                {
                    var user = this.dataManager.User.CreateUser(model.UserName, model.Password, model.Email, false);
                    if (user != null)
                    {
                        this.dataManager.User.AddUserToRole(user.UserId, roleId);
                    }
                }
            }

            return RedirectToAction("Activate");
        }

        public ActionResult Activate(string username = null, string key = null)
        {
            if (username == null && key == null)
            {
                ViewBag.Activate = null;
            }
            else
            {
                this.ViewBag.Activate = this.dataManager.User.ActivateUser(username, key);
                if (ViewBag.Activate)
                {
                    this.FormsService.SignIn(username, true);
                    var userRole = this.dataManager.User.GetRoleUser(username).Role.RoleName;
                    if (userRole == "Employer")
                    {
                        return RedirectToAction("RegisterEmployer");
                    }

                    if (userRole == "Candidate")
                    {
                        return RedirectToAction("RegisterCandidate");
                    }
                }
            }

            return View();
        }

        public ActionResult LogOn(string returnUrl, string userName, string password)
        {
            if (this.dataManager.User.GetDbUser(userName).IsActivated)
            {
                if (AccountModel.LogOn(userName, password))
                {
                    TempData["userName"] = string.Empty;
                    TempData["errorUsernameOrPassword"] = string.Empty;

                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }

                    if (this.RoleService.IsUserInRole(userName, "Candidate"))
                    {
                        return this.dataManager.Candidate.GetCandidateFromUserName(userName) != null ? this.RedirectToAction("Search", "Vacancy") : this.RedirectToAction("RegisterCandidate");
                    }
                    if (this.RoleService.IsUserInRole(userName, "Employer"))
                    {
                        return this.dataManager.Employer.GetEmployerFromUserName(userName) != null ? this.RedirectToAction("Search", "Resume") : this.RedirectToAction("RegisterEmployer");
                    }
                }
                else
                {
                    TempData["username"] = userName;
                    TempData["errorUsernameOrPassword"] = "Неверные имя пользователя и пароль";
                }
            }
            else
            {
                TempData["username"] = userName;
                TempData["errorUsernameOrPassword"] = "Аккаунт не активирован.";
            }

            return RedirectToAction("Index", "Home");
        }

        public ActionResult LogOff()
        {
            AccountModel.LogOff();
            return RedirectToAction("Index", "Home");
        }

        public ActionResult RegisterCandidate()
        {
            return View();
        }

        [HttpPost]
        public ActionResult RegisterCandidate(Candidate candidate)
        {
            this.dataManager.Candidate.CreateCandidate(candidate);
            return RedirectToAction("Search", "Vacancy");
        }

        public ActionResult RegisterEmployer()
        {
            return View();
        }

        [HttpPost]
        public ActionResult RegisterEmployer(Employer employer)
        {
            this.dataManager.Employer.CreateEmployer(employer);
            return RedirectToAction("Search", "Resume");
        }

        public ActionResult PostActivateCode(string userName)
        {
            var user = this.dataManager.User.GetDbUser(userName);
            this.dataManager.User.PostActivateCode(user);
            return View("Activate");
        }
    }
}